#include "TempActorManager.h"

#include "Core/MainWindow.h"
#include <vtkActor.h>
#include "RWTools.h"

float TempActorManager::m_defaultRadius = 0.01f;

TempActorManager::TempActorManager(MainWindow* mainWindow)
	:m_mainWindow(mainWindow)
{
}

TempActorManager::~TempActorManager()
{
	m_allocatedActors.clear();
	m_unallocatedActors.clear();
}

uint8_t TempActorManager::GetUnallocatedActor(float radius)
{
	static unsigned int IDs = 0;

	unsigned int actorId = 0;
	vtkSmartPointer<vtkActor> actor;

	// 未分配的为空
	if (m_unallocatedActors.empty())
	{
		actor = m_mainWindow->CreateTempSphereActor(m_defaultRadius, gp_Pnt());
		actorId = IDs++;
	}
	else
	{
		auto iter = m_unallocatedActors.begin();
		actorId = iter->first;
        actor = iter->second;
        m_unallocatedActors.erase(iter);
	}

	if (!IsNearlyEqual(radius, m_defaultRadius))
	{
		actor->SetScale(radius / m_defaultRadius);
	}
	m_allocatedActors[actorId] = actor;

	return actorId;
}

void TempActorManager::FreeActor(uint8_t actorId)
{
	if (m_allocatedActors.find(actorId) != m_allocatedActors.end())
	{
		vtkSmartPointer<vtkActor> actor = m_allocatedActors[actorId];
		actor->SetVisibility(false);
		actor->SetScale(1.0);
		m_unallocatedActors[actorId] = actor;
		m_allocatedActors.erase(actorId);
		m_mainWindow->FlushRender();
	}
}

void TempActorManager::SetActorVisible(uint8_t actorId, bool bVisible, const gp_Pnt& position)
{
	if (m_allocatedActors.find(actorId) != m_allocatedActors.end())
	{
		m_allocatedActors[actorId]->SetVisibility(bVisible);
		m_allocatedActors[actorId]->SetPosition(position.X(), position.Y(), position.Z());
		m_mainWindow->FlushRender();
	}
}
